<template>
  <div class="mainsu">
    <div>
      <div class="main_white paddingBottom20">
        <div class="mainor_form">
          <div class="mainor_te">
            <el-button @click="exportbuVisible = true"> 导出 </el-button>
          </div>
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="70px"
          >
            <el-form-item label="账单号" prop="order_sn">
              <el-input
                v-model.trim="form.order_sn"
                placeholder="账单号"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item label="账期" prop="payment_days">
              <el-date-picker
                v-model="form.payment_days"
                type="month"
                placeholder="选择月"
                value-format="yyyy-MM"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model.trim="form.status"
                placeholder="状态"
                class="wid220"
              >
                <el-option label="所有" value="0"></el-option>
                <el-option
                  v-for="(typeList, index) in pay_status_list"
                  :key="index"
                  :label="typeList"
                  :value="parseFloat(index + 1)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="createTime"
                type="daterange"
                class="time220"
                :editable="false"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="pickerOptions"
              />
            </el-form-item>

            <div class="clearfix"></div>

            <el-form-item class="marginTop10">
              <el-button
                class="reset marginLeft10"
                type="primary"
                @click="reset"
                >重置</el-button
              >
              <el-button
                type="primary"
                @click="getArticleList"
                :loading="listLoading"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="main_num boxdq">
          <div class="main_num_l box">
            <!-- <p>
              <em
                >暂未</em
              >
            </p> -->
          </div>
        </div>
        <div class="main_table marginTop10" style="min-height: 550px">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            :header-cell-class-name="this.$verticaline"
          >
            <el-table-column label="账单号" width="200" prop="order_sn" />
            <el-table-column label="账期" prop="">
              <template slot-scope="scope">
                {{ parseTime(scope.row.payment_days, "{y}-{m}") }}
              </template>
            </el-table-column>

            <el-table-column label="配送金额" prop="send_money" />
            <el-table-column label="佣金比例" prop="commission_rate">
              <template slot-scope="scope">{{
                scope.row.commission_rate
              }}</template>
            </el-table-column>
            <el-table-column label="佣金金额" prop="commission">
              <template slot-scope="scope">{{
                scope.row.commission ? scope.row.commission : ""
              }}</template>
            </el-table-column>
            <el-table-column label="抹零金额" prop="zero_money">
              <template slot-scope="scope">
                {{ scope.row.zero_money }}
              </template>
            </el-table-column>
            <el-table-column label="实付金额" prop="real_money" />
            <el-table-column label="状态" prop="pay_status">
              <template slot-scope="scope"
                ><span :class="'type' + scope.row.pay_status">
                  {{ pay_status_list[scope.row.pay_status] }}
                </span></template
              >
            </el-table-column>
            <el-table-column label="支付剩余时间（天）" width="200">
              <template slot-scope="scope"
                >{{ scope.row.pay_status == 0 ? scope.row.surplus : 0 }}
              </template>
            </el-table-column>

            <el-table-column label="创建时间" prop="status" width="120">
              <template slot-scope="scope">{{
                scope.row.created_at
                  ? parseTime(scope.row.created_at, "{y}-{m}-{d}")
                  : ""
              }}</template>
            </el-table-column>

            <el-table-column
              label="管理操作"
              align="center"
              fixed="right"
              width="100"
              class-name="main_hei handle"
            >
              <template slot-scope="scope">
                <span
                  v-if="scope.row.pay_status == 0"
                  class="pay"
                  @click="knotClick(scope)"
                  >支付</span
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <el-pagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
      <!-- 二维码 -->
      <el-dialog
        title="二维码"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="addedFormVisible"
        class="main_dialog dialog500"
        @close="commission_close"
      >
        <div class="qrcode_box">
          <p>
            金额：<span>{{ qrcode_box_info.real_money }}元</span>
          </p>
          <p>账单号：{{ qrcode_box_info.order_sn }}</p>
        </div>
        <div
          id="qrcode"
          style="margin: auto; width: 200px"
          class="marginTop20 marginBottom20"
        ></div>
      </el-dialog>

      <!-- 订单导出 -->
      <el-dialog
        title="在线支付佣金账单导出"
        :visible.sync="exportbuVisible"
        class="main_dialog dialog500"
      >
        <p class="exptitle">选择导出时间</p>
        <el-date-picker
          v-model="exportTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="dateChange"
        >
        </el-date-picker>
        <el-tooltip
          class="item"
          effect="dark"
          content="时间范围只能选择两个月之内"
          placement="top"
        >
          <i class="el-icon-question"></i>
        </el-tooltip>

        <div slot="footer" class="dialog-footer">
          <el-button @click="exportbuVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleExport" v-repeatClick
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  commission_offline,
  commission_pay,
  commission_query,
  commission_close,
  exportOffline,
} from "@/api/financial/finacialCommission";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import dateOption from "@/options/dateOption";
import QRCode from "qrcodejs2";
import { parseTime, exportMethod, getNowMonth } from "@/utils/index";

export default {
  components: {},
  data() {
    return {
      // 时间
      parseTime,
      exportMethod,
      getNowMonth,
      // 列表数据
      list: [],
      listLoading: false,
      pay_status_list: {},
      // 搜索
      form: {
        order_sn: "", //单号
        payment_days: "", //账期
        status: null, //结算状态
        start_time: "", //结算日期
        end_time: "",
      },
      createTime: [],
      pickerOptions: dateOption,
      // 更多
      moredata: false,
      // 全选
      selectArr: [],
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 0,

      qrCodeId: "",
      qrcode_box_info: {
        order_sn: "",
        real_money: "",
      },
      addedFormVisible: false,
      query_timer: "",
      query_error_message: "",
      query_success_message: "",
      exportTime: [],
      export_uid: "",
      exportbuVisible: false,
      is_pay: false,
    };
  },
  created() {
    this.commission_offline();
  },
  methods: {
    // 订单差额 ？注释
    renderHeader_purchase(h, { column, $index }) {
      // 这里在最外层插入一个div标签
      return h("div", [
        // h即为cerateElement的简写
        // 在div里面插入span
        h("span", {
          // 表示内容
          domProps: {
            innerHTML: column.label,
          },
          on: {
            click: () => {
              console.log(`${column.label}   ${$index}`);
            },
          },
        }),
        h(
          "el-tooltip",
          {
            // 表示属性
            attrs: {
              effect: "dark",
              content: "注释：差异金额=下单金额-对账金额",
              placement: "top",
            },
          },
          [
            h("i", {
              style: "margin-left: 5px;margin-top:-1px;",
              class: "el-icon-question table-msg",
            }),
          ]
        ),
      ]);
    },
    // 支付
    knotClick(scope) {
      let id = scope.row.id;
      this.commission_pay(id);
    },
    // 支付请求二维码
    commission_pay(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      commission_pay(data).then((res) => {
        if (res.errcode == 0) {
          this.addedFormVisible = true;
          this.qrcode_box_info = res.data.info;
          this.qrCodeId = JSON.parse(res.data.res).qrCodeId;
          this.$nextTick(() => {
            let qrcode = new QRCode("qrcode", {
              width: 200,
              height: 200,
              text: JSON.parse(res.data.res).billQRCode,
            });
            this.query_timer = setInterval(() => {
              this.commission_query(res.data.info.id);
            }, 1000);
          });
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 查询支付
    commission_query(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      commission_query(data).then((res) => {
        if (res.errcode == 0) {
          this.query_success_message = res.errmsg;
          this.is_pay = true;
          if (this.query_success_message != res.errmsg) {
            this.$message.success("支付成功");
            this.query_success_message = res.errmsg;
          }
          document.getElementById("qrcode").innerHTML = "";
          clearInterval(this.query_timer);
          this.query_timer = "";
          this.addedFormVisible = false;
          this.commission_offline();
        } else {
          if (
            this.query_error_message != res.errmsg &&
            res.errmsg != "未支付"
          ) {
            this.$message.error(res.errmsg);
            this.query_error_message = res.errmsg;
          }
        }
      });
    },
    // 订单关闭
    commission_close() {
      document.getElementById("qrcode").innerHTML = "";
      clearInterval(this.query_timer);
      this.query_timer = "";
      this.addedFormVisible = false;
      let id = this.qrcode_box_info.id;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      if (!this.is_pay) {
        commission_close(data).then((res) => {
          if (res.errcode == 0) {
            this.$message.error("支付失败!");
            // this.commission_offline();
          } else {
            this.$message.error(res.errmsg);
          }
        });
      } else {
      }
    },

    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.commission_offline();
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.createTime = [];
      this.commission_offline();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.commission_offline();
    },
    changePage(page) {
      this.current.page = page;
      this.commission_offline();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 列表
    commission_offline() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      commission_offline(data).then((res) => {
        if (res.errcode == 0) {
          this.listLoading = false;
          res.data.list.data.map((e) => {
            let forbid_days = new Date(e.forbid_days).getTime();
            let created_at = new Date().getTime();
            let dateSpan = forbid_days * 1000 - created_at;
            e.surplus = Math.ceil(dateSpan / (24 * 3600 * 1000));
            if (e.surplus < 0) {
              e.surplus = 0;
            }
          });
          this.list = res.data.list.data;
          this.totalCount = res.data.list.total;
          this.pay_status_list = res.data.pay_status_list;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = this.createTime[0] ? this.createTime[0] : "";
      form.end_time = this.createTime[1] ? this.createTime[1] : "";
      return form;
    },
    // 导出
    handleExport() {
      if (this.exportTime.length == 0) {
        this.$message.warning("请选择需要导出的时间段");
        return;
      }
      let form = {
        start_time: "",
        end_time: "",
      };

      if (this.exportTime && this.exportTime.length > 0) {
        form.start_time = this.exportTime[0];
        form.end_time = this.exportTime[1];
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, form)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      exportOffline(data).then((res) => {
        this.exportMethod(res, "货到付款佣金账单");
      });

      this.exportbuVisible = false;
      this.$nextTick(() => {
        this.exportTime = [];
      });
    },
    // 日期选择
    dateChange(val) {
      let start = val ? new Date(val[0]).getTime() : 0;
      let end = val ? new Date(val[1]).getTime() : 0;
      let diff = start - end;
      if (Math.abs(diff) > 3600 * 1000 * 24 * 60) {
        this.$message.warning("选择时间跨度不能超过两个月");
        this.exportTime = this.getNowMonth();
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 180px);
  }

  .main_dialog {
    .main_xq {
      /deep/.el-form-item--small.el-form-item {
        margin-bottom: 0;
      }
    }

    .main_table {
      /deep/.el-table__body-wrapper {
        overflow-y: auto;
        height: 400px;
      }
      /deep/.el-table--small td {
        padding-top: 0;
      }
      /deep/.el-form-item--small.el-form-item {
        margin-bottom: 16px;
        margin-top: 16px;
        margin-right: 0;
      }
    }
    .main_xq ul li {
      width: 33.33%;
      margin-top: 5px;
      margin-bottom: 5px;
      .main_xqs {
        width: 85%;
        display: block;
        text-align: left;
        /deep/.el-input--small {
          width: 100%;
        }
      }
    }
    .footer_red {
      font-size: 16px;
      color: red;
      margin-right: 10px;
    }
  }
}
// 支付状态
.type0 {
  color: $colour_red;
}
.type1 {
  color: $green;
}
.type2 {
  color: #cccccc;
}
// 订单状态
.order0 {
  color: $order_color4;
}
.order1 {
  color: $order_color1;
}
.pay {
  cursor: pointer;
  color: $green;
}
.qrcode_box {
  font-size: 16px;
  margin: auto;
  width: 250px;
  p {
    line-height: 1.5;
    &:first-child {
      span {
        color: red;
        font-size: 18px;
        font-weight: 700;
      }
    }
  }
}
// 导出订单表头
.exptitle {
  display: block;
  font-size: 16px;
  color: #000000;
  margin: 0 0 10px;
  cursor: pointer;
}
</style>
